<template>
  <div class="table-grobal">
    <!-- 表单 -->
    <div class="varietyForm">
      <el-dialog
        :title="operateType === 'add' ? '添加菜品内容' : '菜品更新'"
        :visible.sync="isShow"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item
            label="菜品分类"
            :label-width="formLabelWidth"
            prop="classification"
          >
            <el-select
              v-model="ruleForm.classification"
              placeholder=""
              style="width: 100%"
            >
              <el-option
                v-for="item in classification"
                :key="item.lable"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="菜品名"
            prop="name"
            :label-width="formLabelWidth"
          >
            <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="菜品价格"
            prop="price"
            :label-width="formLabelWidth"
          >
            <el-input v-model="ruleForm.price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="菜品上架状态 "
            prop="state"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="ruleForm.state"
              placeholder=""
              style="width: 100%"
            >
              <el-option label="已上架" value="已上架"></el-option>
              <el-option label="已下架" value="已下架"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销量" prop="sell" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.sell" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="创建时间"
            prop="creatTime"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              type="date"
              placeholder=""
              v-model="ruleForm.creatTime"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              autocomplete="off"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            label="更新时间"
            prop="updateTime"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              type="date"
              placeholder=""
              v-model="ruleForm.updateTime"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              autocomplete="off"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <!-- 搜索框 -->
    <div class="operation">
      <el-button type="primary" @click="add" style="margin-top: 0"
        >+ 新增</el-button
      >
      <div style="margin-top: 0" class="search">
        <el-input
          placeholder="请输入检索词"
          v-model="keyword"
          class="input-with-select"
          @keyup.enter.native="searchEnterFun"
          clearable
        ></el-input>
        <el-button
          type="primary"
          style="margin-top: 0"
          icon="el-icon-search"
          @click="getList(keyword)"
          >搜索
        </el-button>
      </div>
    </div>
    <!-- 菜品信息表 -->
    <div class="info">
      <el-table
        :data="
          tableList.slice((currentPage - 1) * PageSize, currentPage * PageSize)
        "
        border
        style="width: 100%"
      >
        <!-- :default-sort="{ prop: 'price', order: 'ascending' }" -->
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          v-for="item in tableTitle"
          :key="item.prop"
          :prop="item.prop"
          :label="item.lable"
          :width="item.width"
          :sortable="item.sortable"
        >
        </el-table-column>
        <el-table-column prop="img" label="菜品图片" align="center" width="220">
          <template slot-scope="scope">
            <img :src="scope.row.ImageUrl" style="height: 80px; width: 120px" />
            <div class="DownloadSigned">
              <span class="download" @click="downloadImg(scope.row.ImageUrl)"
                >下载图片</span
              >
              <span class="Copy" @click="copyLink(scope.row.ImageUrl)"
                >访问链接 <i class="el-icon-document-copy"></i
              ></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row, scope.$index)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="pageSizes"
        :page-size="PageSize"
        :pager-count="5"
        layout="total, prev, pager, next, sizes"
        :total="this.tableList.length"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import dapanji from "@/assets/tableimg/dapanji.jpg";
import kaoji from "@/assets/tableimg/kaoji.jpg";
import kaoyu from "@/assets/tableimg/kaoyu.jpg";
import dazhutizi from "@/assets/tableimg/dazhutizi.jpg";
import kaoya from "@/assets/tableimg/kaoya.jpg";
export default {
  name: "tablesGlobal",
  data() {
    return {
      isShow: false,
      formLabelWidth: "120px",
      operateType: "",
      isShow: false,
      classification: [
        {
          label: "新品推荐",
          value: "新品推荐",
        },
        {
          label: "店长推荐",
          value: "店长推荐",
        },
        {
          label: "主食",
          value: "主食",
        },
        {
          label: "经典套餐",
          value: "经典套餐",
        },
        {
          label: "面食",
          value: "面食",
        },
        {
          label: "粥品汤类",
          value: "粥品汤类",
        },
        {
          label: "酒水饮料",
          value: "酒水饮料",
        },
      ],
      ruleForm: {
        classification: "",
        name: "",
        price: "",
        state: "",
        sell: "",
        img: "",
        creatTime: "",
        updateTime: "",
      },
      rules: {
        classification: [
          { required: true, message: "请选择菜品分类", trigger: "change" },
        ],
      },
      tableTitle: [
        {
          prop: "classification",
          lable: "菜品分类",
          width: "120",
        },
        {
          prop: "name",
          lable: "菜品名",
          width: "166",
        },
        {
          prop: "price",
          lable: "菜品价格",
          width: "120",
          // sortable: "",
        },
        {
          prop: "state",
          lable: "菜品上架状态",
          width: "120",
        },
        {
          prop: "sell",
          lable: "销量",
          width: "120",
          // sortable: "",
        },
        {
          prop: "creatTime",
          lable: "创建时间",
          width: "160",
          // sortable: "",
        },
        {
          prop: "updateTime",
          lable: "修改时间",
          width: "160",
          // sortable: "",
        },
      ],
      tableData: [
        {
          classification: "经典套餐",
          name: "红烧牛肉套餐",
          price: "22.00",
          state: "已上架",
          sell: "0",
          creatTime: "2022-04-20",
          updateTime: "2022-04-21",
          ImageUrl: dapanji,
        },
        {
          classification: "经典套餐",
          name: "梅菜扣肉",
          price: "18.00",
          state: "已上架",
          sell: "4",
          creatTime: "2022-04-22",
          updateTime: "2022-04-21",
          ImageUrl: kaoji,
        },
        {
          classification: "经典套餐",
          name: "鱼香肉丝",
          price: "26.00",
          state: "已上架",
          sell: "5",
          creatTime: "2022-04-21",
          updateTime: "2022-04-21",
          ImageUrl: kaoyu,
        },
        {
          classification: "经典套餐",
          name: "猪脚饭",
          price: "24.00",
          state: "已上架",
          sell: "3",
          creatTime: "2022-04-23",
          updateTime: "2022-04-21",
          ImageUrl: dazhutizi,
        },
        {
          classification: "经典套餐",
          name: "东北饺子",
          price: "20.00",
          state: "已上架",
          sell: "2",
          creatTime: "2022-04-19",
          updateTime: "2022-04-21",
          ImageUrl: kaoya,
        },
        {
          classification: "经典套餐",
          name: "鱼香肉丝",
          price: "26.00",
          state: "已上架",
          sell: "5",
          creatTime: "2022-04-21",
          updateTime: "2022-04-21",
          ImageUrl: kaoya,
        },
        {
          classification: "经典套餐",
          name: "东北饺子",
          price: "20.00",
          state: "已上架",
          sell: "2",
          creatTime: "2022-04-19",
          updateTime: "2022-04-21",
          ImageUrl: dazhutizi,
        },
        {
          classification: "经典套餐",
          name: "鱼香肉丝",
          price: "26.00",
          state: "已上架",
          sell: "5",
          creatTime: "2022-04-21",
          updateTime: "2022-04-21",
          ImageUrl: kaoyu,
        },
        {
          classification: "经典套餐",
          name: "东北饺子",
          price: "20.00",
          state: "已上架",
          sell: "2",
          creatTime: "2022-04-19",
          updateTime: "2022-04-21",
          ImageUrl: kaoji,
        },
        {
          classification: "经典套餐",
          name: "鱼香肉丝",
          price: "26.00",
          state: "已上架",
          sell: "5",
          creatTime: "2022-04-21",
          updateTime: "2022-04-21",
          ImageUrl: dapanji,
        },
      ],
      varietyIndex: 0,
      keyword: "",
      searchForm: {
        keyword: "",
      },
      tableList: [],
      searchlist: [],
      currentPage: 1,
      pageSizes: [5, 10, 20],
      PageSize: 5,
    };
  },

  methods: {
    // 创建
    add() {
      this.isShow = true;
      this.operateType = "add";
    },

    // 取消按钮
    cancel(formName) {
      this.$refs[formName].resetFields();
      this.isShow = false;
    },

    // 添加菜品
    submitForm(formName) {
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     alert("submit!");
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
      if (!this.ruleForm.classification) {
        this.$message({
          message: "警告，请输入菜品分类",
          type: "warning",
        });
        return;
      }
      this.isShow = false;
      // console.log(this.operateType)
      if (this.operateType === "add") {
        this.tableData.push(this.ruleForm);
        this.ruleForm = {
          classification: "",
          name: "",
          price: "",
          state: "",
          sell: "",
          creatTime: "",
          updateTime: "",
        };
      } else {
        console.log(this.operateType);

        this.tableData.splice(this.varietyIndex, 1, this.ruleForm);
      }
      // console.log(this.operateType)
      // console.log(this.tableData)
      this.tableList = this.tableData;
    },

    // 更新菜品
    handleEdit(row, index) {
      // console.log(row);
      this.varietyIndex = index;
      this.ruleForm = {
        classification: row.classification,
        name: row.name,
        price: row.price,
        state: row.state,
        sell: row.sell,
        creatTime: row.creatTime,
        updateTime: row.updateTime,
      };
      this.isShow = true;
      this.operateType = "edit";
      // console.log(this.operateType);
    },
    // 删除菜品
    handleDelete(index, row) {
      // console.log(index);
      this.$confirm("确认删除？")
        .then((_) => {
          this.tableData.splice(index, 1);
        })
        .catch((_) => {});
      // console.log(this.tableData)
      this.tableList = this.tableData;
    },

    // 回车
    searchEnterFun(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      // console.log("回车搜索", keyCode, e);
      if (keyCode == 13) {
        this.getList();
      }
    },

    // 搜索
    setSlist(arr) {
      this.tableList = JSON.parse(JSON.stringify(arr));
    },

    getList() {
      console.log(this.keyword);
      if (!this.keyword) {
        this.$message({
          message: "警告，请输入检索词",
          type: "error",
        });
        return;
      }
      // const keyword = this.keyword
      // if(keyword){
      //   return this.tableData.filter((item) => {
      //     return Object.keys(item).some((key) => {
      //       // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
      //       // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
      //       return String(item[key]).toLowerCase().indexOf(keyword) > -1;
      //     });
      //   });
      // }
      // return this.tableData;
      if (this.keyword) {
        var slist = [];
        // 过滤需要的数据
        this.tableData.forEach((item) => {
          // 检测搜索关键字
          if (item.name.indexOf(this.keyword) > -1) {
            slist.push(item);
          }
        });
        this.setSlist(slist); // 将过滤后的数据给了tableList
      }
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      // 改变每页显示的条数
      this.PageSize = val;
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      // 改变默认的页数
      this.currentPage = val;
    },

    // 下载图片
    downloadImg(ImageUrl) {
      console.log(ImageUrl);
      var a = document.createElement("a");
      a.download = name || "pic";
      // 设置图片地址
      a.href = ImageUrl;
      a.click();
      this.$message.success("下载成功");
    },

    // 复制图片链接
    copyLink(ImageUrl) {
      console.log(ImageUrl);
      let url = ImageUrl; // 后台接口返回的链接地址
      let inputNode = document.createElement("input"); // 创建input
      inputNode.value = url; // 赋值给 input 值
      document.body.appendChild(inputNode); // 插入进去
      inputNode.select(); // 选择对象
      document.execCommand("Copy"); // 原生调用执行浏览器复制命令
      inputNode.className = "oInput";
      inputNode.style.display = "none"; // 隐藏
      this.$message.success("复制成功");
    },
  },

  created() {
    this.setSlist(this.tableData);
  },
};
</script>

<style lang="less" scoped>
.table-grobal {
  margin: 20px;
}
.varietyForm {
  margin-bottom: 20px;
}
.operation {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .search {
    display: flex;
  }
}

.block {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.DownloadSigned {
  color: #0052d9;
  .download {
    cursor: pointer;
    margin-right: 10px;
  }
  .Copy {
    cursor: pointer;
    margin-left: 10px;
  }
}
</style>
